<template>
  <div class="bodyClass">
    <!-- 四叶草 -->
    <div class="box">
      <!-- 四叶草的单片叶子 -->
      <div class="clover"></div>
      <div class="clover"></div>
      <div class="clover"></div>
      <div class="clover"></div>
    </div>
    <!-- 表单盒子 -->
    <div class="form-box">
      <!-- 登录盒子 -->
      <div class="login-box">
        <!-- 标题 -->
        <h1 class="title">登录</h1>
        <!-- 图片盒子 -->
        <div class="img-box">
          <!-- 图片 -->
          <img src="@/assets/胡桃.jpg" alt="" />
        </div>
        <!-- 输入框盒子 -->
        <div class="input-box">
          <!-- 输入框 -->
          <input
            type="text"
            placeholder="用户名"
            v-model="loginData.username"
          />
          <input
            type="password"
            placeholder="密码"
            v-model="loginData.userPassworld"
          />
        </div>
        <!-- 按钮盒子 -->
        <div class="btn-box">
          <button @click="loginFunction">登录</button>
          <!-- 绑定点击事件 -->
          <span @click="init">注册</span>
        </div>
      </div>
      <!-- 注册盒子 -->
      <div class="register-box">
        <!-- 标题 -->
        <h1 class="title" style="margin-bottom: 20px">注册</h1>
        <!-- 图片盒子 -->
        <!-- <div class="img-box">
                  <img src="@/assets/可莉.png" alt="">
              </div> -->
        <!-- 输入框盒子 -->
        <div class="input-box">
          <!-- 输入框 -->
          <input
            type="text"
            placeholder="用户名"
            v-model="registerData.username"
          />
          <input
            type="password"
            placeholder="密码"
            v-model="registerData.userPassworld"
            @blur="blur('密码')"
          />
          <input
            type="password"
            placeholder="确认密码"
            v-model="registerData.requerPassworld"
            @blur="blur('密码')"
          />
          <input
            type="text"
            placeholder="手机号"
            v-model="registerData.cellphoneNumber"
            @input="
              registerData.cellphoneNumber = checkoutNumber(
                registerData.cellphoneNumber,
                11,
                0
              )
            "
            @blur="blur('手机号')"
          />
          <input
            type="text"
            placeholder="验证码"
            v-model="registerData.phoneCode"
            @input="
              registerData.phoneCode = checkoutNumber(registerData.phoneCode, 4,0)"
          />
          <button
            type="button"
            class="codeButtonClass"
            @click="clickCodeHandler"
            :disabled="codeDisable"
            :class="{
              codeDisableClass: !codeDisable,
              noCodeDisableClass: codeDisable,
            }"
          >
            <span v-show="!codeDisable">发送验证码</span>
            <span v-show="codeDisable">{{ countTime }}s 后重新获取</span>
          </button>
        </div>
        <!-- 按钮盒子 -->
        <div class="btn-box">
          <button @click="registerFunction">注册</button>
          <!-- 绑定点击事件 -->
          <span @click="init">登录</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getDateFUnction} from '@/components/config/index'
import { checkoutNumber,algorithm } from "@/components/config/index";
import { obtainVerificationCode , registerUserFUnction,loginUserFUnction } from "@/api/login";
export default {
  name: "login",
  data() {
    return {
      flag: true,
      loginData: {
        username: "",
        userPassworld: "",
      },
      registerData: {
        username: "",
        userPassworld: "",
        requerPassworld: "",
        cellphoneNumber: "",
        phoneCode: "",
      },
      codeDisable: false,
      countTime: "",
      timer: null,
      jiaoyan: {
        phone: false,
        // phoneNumber:'',
        serveCode: "",
      },
    };
  },
  mounted() {
    sessionStorage.removeItem( 'userMessage' )
  },
  methods: {
    checkoutNumber,
    init() {
      document.querySelector(".register-box").style.opacity = this.flag ? 1 : 0;
      document.querySelector(".register-box").style.top = this.flag
        ? "0px"
        : "420px";
      document.querySelector(".login-box").style.opacity = this.flag ? 0 : 1;
      document.querySelector(".login-box").style.top = this.flag
        ? "-420px"
        : "0px";
      // 每次点击都改变状态
      this.flag = !this.flag;
    },

    loginFunction() {
      if (!this.loginData.username) {
        this.$notify.error({ title: "错误", message: "用户名不能为空" });
        return;
      }
      if (!this.loginData.userPassworld) {
        this.$notify.error({ title: "错误", message: "密码不能为空" });
        return;
      }
      //发送网络请求
      loginUserFUnction(this.loginData).then(res=>{
        console.log('登录返回结果',res)
        if(res.data.code == '200'){
            this.$notify.success({ title: "提示", message: "登录成功" });
            sessionStorage.setItem('userMessage',JSON.stringify(res.data.message) )
            this.$router.push("/homePage");
        }else{
            this.$notify.warning({ title: "提示", message: res.data.message });
        }
      })
    },
    //手机号失焦事件
    blur(str) {
      console.log("触发失焦事件", str);
      if (str == "手机号") {
        if (this.registerData.cellphoneNumber == "") return;
        if (!/^1[3-9]\d{9}$/.test(this.registerData.cellphoneNumber)) {
          this.$notify.warning({
            title: "提示",
            message: "请输入合法手机号码",
          });
          this.jiaoyan.phone = false;
          return;
        }
        this.jiaoyan.phone = true;
      }
      if (str == "密码") {
        if (this.registerData.userPassworld == "") return;
        if (this.registerData.requerPassworld == "") return;
        if (
          this.registerData.userPassworld != this.registerData.requerPassworld
        )
          this.$notify.warning({
            title: "提示",
            message: "两次密码输入的不一致",
          });
      }
    },
    //点击发送验证码
    clickCodeHandler() {
      if (this.registerData.cellphoneNumber == "")
        this.$notify.warning({ title: "提示", message: "请输入合法手机号码" });
      if (!this.jiaoyan.phone) return;
      this.getCode();
      let prm = {
        cellphoneNumber: this.registerData.cellphoneNumber,
      };
      obtainVerificationCode(prm).then((res) => {
        console.log("验证码返回的数据", res);
        if (res.data.code == "401") {
          this.$notify.warning({ title: "提示", message: res.data.message });
          this.codeDisable = false
          return;
        }
        if (res.data.code != "200") {
          this.$notify.warning({ title: "提示", message: "验证码服务端错误" });
          console.log("验证码错误", res.data.message);
          return;
        }
        this.jiaoyan.serveCode = res.data.message.body.params[0];
      });
    },
    //倒计时
    getCode() {
      const TIME_COUNT = 120;
      if (!this.timer) {
        this.countTime = TIME_COUNT;
        this.codeDisable = true;
        this.timer = setInterval(() => {
          if (this.countTime > 0 && this.countTime <= TIME_COUNT)
            this.countTime--;
          else {
            this.codeDisable = false;
            this.jiaoyan.serveCode = -1
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },

    registerFunction() {
      let mes = this.yanzhengGuize()
      if(mes.code != '200') return
      this.registerData.userId = algorithm()
      this.registerData.userEntryTime = getDateFUnction()
      console.log('用户注册参数',this.registerData)
      registerUserFUnction(this.registerData).then(res=>{
        console.log("用户注册结果",res)
        if(res.data.code == '200' ) {
            this.$notify.success({ title: "提示", message: res.data.message });
           this.reloadFunction()
        }
        else this.$notify.warning({ title: "提示", message: res.data.message });
      })
    },
    yanzhengGuize() {
      try {
        if (this.registerData.username == "") throw new Error("用户名不能为空");
        if (this.registerData.userPassworld == "") throw new Error("密码不能为空");
        if (this.registerData.requerPassworld == "") throw new Error("请确认密码");
        if (this.registerData.cellphoneNumber == "")  throw new Error("请输入手机号");
        if (this.jiaoyan.serveCode == -1)  throw new Error("验证码已失效，请重新获取");
        if (this.jiaoyan.serveCode == -2)  throw new Error("手机号已更改，请重新获取");
        if (this.registerData.phoneCode == "") throw new Error("请输入四位数验证码");
        if(this.registerData.phoneCode != this.jiaoyan.serveCode )  throw new Error("验证码校验错误");
        return { code: "200", mes: "成功" };
      } catch (m) {
        this.$notify.warning({ title: "提示", message: m.message });
        return { code: "404", mes: "失败" };
      }
    },
    //注册成功后页面重置
    reloadFunction(){
        this.loginData.username = ''
        this.loginData.userPassworld = ''
        this.registerData.username = ''
        this.registerData.userPassworld = ''
        this.registerData.requerPassworld = ''
        this.registerData.cellphoneNumber = ''
        this.registerData.phoneCode = ''
        this.init()
    }
  },
  watch:{
    'registerData.cellphoneNumber':{
        handler(newVAl){
            if(this.jiaoyan.serveCode != '' && this.jiaoyan.serveCode != -1) 
                this.jiaoyan.serveCode = -2
        }
    }
  }
};
</script>

<style scoped>
.bodyClass {
  height: 100vh;
  /* 溢出隐藏 */
  overflow: hidden;
  /* 设置弹性布局 */
  display: flex;
  justify-content: center;
  align-items: center;
  /* 设置渐变色 */
  background: linear-gradient(to right, #e6a49d, #fff);
}

/* 四叶草 */
.box {
  width: 500px;
  height: 500px;
  display: flex;
  /* 设置换行 */
  flex-wrap: wrap;
  /* 动画，转动 */
  animation: myRotate 10s linear infinite;
}

/* 单片四叶草，正方形 */
.clover {
  width: 200px;
  height: 200px;
  background-color: #e6a49d;
  border: 1px solid #fff;
}

/* 单片四叶草，圆形 */
.clover::before {
  content: "";
  width: 200px;
  height: 200px;
  background-color: #e6a49d;
  position: absolute;
  border-radius: 50%;
  transform: translateX(-100px);
}

/* 单片四叶草，圆形 */
.clover::after {
  content: "";
  width: 200px;
  height: 200px;
  background-color: #e6a49d;
  position: absolute;
  border-radius: 50%;
  transform: translateY(-100px);
}

/* 设置水平竖直方向的位置，以及旋转角度 */
.clover:nth-child(1) {
  transform: translate(52px, 52px);
}

.clover:nth-child(2) {
  transform: translate(52px, 52px) rotate(90deg);
}

.clover:nth-child(3) {
  transform: translateX(52px) rotate(-90deg);
}

.clover:nth-child(4) {
  transform: translateX(52px) rotate(180deg);
}

/* 旋转动画 */
@keyframes myRotate {
  25% {
    transform: rotate(90deg);
  }

  50% {
    transform: rotate(180deg);
  }

  75% {
    transform: rotate(270deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 表单盒子 */
.form-box {
  position: absolute;
  right: 20%;
  width: 400px;
  height: 500px;
  border-radius: 5px;
  /* 模糊，磨砂质感 */
  backdrop-filter: blur(10px);
  box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
  z-index: 99;
  overflow: hidden;
}
.login-box {
  position: absolute;
  top: 0px;
  opacity: 1;
  width: 100%;
  /* top: -420px;    */
}
/* 一开始隐藏注册盒子 */
.register-box {
  position: absolute;
  /* top: 0px;   */
  top: 420px;
  opacity: 0;
  width: 100%;
}
.login-box,
.register-box {
  /* 过渡动画 */
  transition: all 1s ease-in-out;
}

/* 标题 */
.title {
  margin-top: 50px;
  text-align: center;
  /* 设置用户禁止选中 */
  user-select: none;
  font-family: "华文行楷";
  color: #fff;
  /* 文字阴影 */
  text-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
}

/* 图片盒子 */
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px auto;
  user-select: none;
  border-radius: 50%;
  /* 溢出隐藏 */
  overflow: hidden;
  box-shadow: 4px 4px 3px rgba(0, 0, 0, 0.1);
}

/* 图片 */
.img-box img {
  width: 100%;
}

/* 输入框盒子 */
.input-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 输入框 */
input {
  outline: none;
  width: 60%;
  height: 40px;
  margin-bottom: 20px;
  text-indent: 10px;
  font-size: 14px;
  font-weight: 500;
  padding-left: 5px;
  background-color: rgba(0, 0, 0, 0);
  color: rgb(49, 49, 49);
  border-radius: 20px;
  border: 1px solid #fff;
}

input::placeholder {
  font-size: 14px;
  font-weight: 400;
}

input:focus::placeholder {
  opacity: 0;
}

/* 按钮盒子 */
.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
}
.btn-box > button {
  margin: 15px 30px;
}
.btn-box > span {
  cursor: pointer;
  font-size: 14px;
  margin: 15px 30px;
}

/* 按钮 */
button {
  width: 100px;
  height: 30px;
  margin-bottom: 10px;
  border: none;
  color: #fff;
  font-size: 16px;
  border-radius: 4px;
  background-color: #c08f8a;
  /* border: 1px solid #e6a49d; */
}

button:hover {
  cursor: pointer;
}
.codeButtonClass {
  position: absolute;
  width: auto;
  bottom: 75px;
  right: 100px;
  font-size: 14px;
  padding: 0px 10px;
}
.codeDisableClass {
  background-color: #bc6e679a;
  cursor: pointer !important;
}
.noCodeDisableClass {
  font-size: 12px;
  background-color: #7974749a;
  cursor: not-allowed !important;
}
</style>
